package com.zkyc.framework.user.config;


import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.PostConstruct;

@Configuration()
@Slf4j
public class JedisPoolFactory {

    @Value("${spring.redis.host}")
    private String redisHost;

    @Value("${spring.redis.port}")
    private Integer redisPort;

    @Value("${spring.redis.password}")
    private String redisPassword;

    private static volatile JedisPool jedisPool;




    @Bean
    public JedisPool JedisPoolInit() {
        log.info("初始化jedis bean:" + redisHost + "redisPort:" + redisPort);
        //定义连接 池配置
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(10);
        jedisPoolConfig.setMaxWaitMillis(1000);
        jedisPoolConfig.setSoftMinEvictableIdleTimeMillis(1800000);
        jedisPoolConfig.setTestWhileIdle(true);
        jedisPoolConfig.setTestOnBorrow(true);
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, redisHost, redisPort,0,redisPassword,0);
        this.jedisPool = jedisPool;
        return jedisPool;
    }

    public static JedisPool getJedisPoolInstance() {
        return jedisPool;
    }

    public static String select(String key) {
        String result = null;
        Jedis resource = null;
        try {
            resource = jedisPool.getResource();
            result = resource.get(key);
        } catch (Exception e) {
            log.info("jedispool获取出错", e);
        } finally {
            resource.close();
        }
        return result;
    }

    public static void delete(String key) {
        Jedis resource = null;
        try {
            resource = jedisPool.getResource();
            resource.del(key);
        } catch (Exception e) {
            log.info("jedis删除出错", e);
        } finally {
            resource.close();
        }
    }

    public static void setex(String key, int daySecond, String value) {
        String result = null;
        Jedis resource = null;
        try {
            resource = jedisPool.getResource();
            result = resource.setex(key,daySecond,value);
        } catch (Exception e) {
            log.info("jedispool获取出错", e);
        } finally {
            resource.close();
        }
    }

}
